package org.example.aienglishapp.util.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class OssService {

    @Autowired
    private OssConfig ossConfig;

    /**
     * 上传文件到 OSS
     * @param file 上传的文件
     * @return 文件在 OSS 中的 URL
     */
    public String uploadFile(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            // 创建 OSSClient 实例
            OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getKeyid(), ossConfig.getKeysecret());

            // 上传文件
            String objectName = "standard/" + file.getOriginalFilename();
            PutObjectResult putObjectResult = ossClient.putObject(ossConfig.getBucketname(), objectName, inputStream);

            // 关闭 OSSClient
            ossClient.shutdown();

            // 返回文件在 OSS 中的 URL
            return "https://" + ossConfig.getBucketname() + "." + ossConfig.getEndpoint() + "/" + objectName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 从 OSS 下载文件
     * @param objectName 文件在 OSS 中的对象名称
     * @return 文件内容的输入流
     */
    public InputStream downloadFile(String objectName) {
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getKeyid(), ossConfig.getKeysecret());

        try {
            // 获取文件输入流
            return ossClient.getObject(ossConfig.getBucketname(), objectName).getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件下载失败", e);
        } finally {
            // 关闭 OSSClient
            ossClient.shutdown();
        }
    }
}
